package com.aiprompt.demos.service.impl;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aiprompt.demos.model.domain.Dict;
import com.aiprompt.demos.model.dto.dict.DictQueryRequest;
import com.aiprompt.demos.service.DictService;
import com.aiprompt.demos.mapper.DictMapper;
import org.springframework.stereotype.Service;

/**
* @author Administrator
* @description 针对表【dict(提示词模板表)】的数据库操作Service实现
* @createDate 2025-08-27 16:48:28
*/
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
    implements DictService{

    /**
     * 拼接查询字段
     * @param dictQueryRequest  模板查询实体
     * @return 查询条件
     */

    @Override
    public QueryWrapper<Dict> getQueryWrapper(DictQueryRequest dictQueryRequest) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        if (dictQueryRequest == null) {
            return queryWrapper;
        }

        // 基础字段处理
        queryWrapper.eq(ObjUtil.isNotNull(dictQueryRequest.getId()), "id", dictQueryRequest.getId());
        queryWrapper.like(StrUtil.isNotBlank(dictQueryRequest.getTitle()), "title", dictQueryRequest.getTitle());
        queryWrapper.like(StrUtil.isNotBlank(dictQueryRequest.getDescription()), "description", dictQueryRequest.getDescription());

        // 新增字段处理
        queryWrapper.eq(StrUtil.isNotBlank(dictQueryRequest.getCategory()), "category", dictQueryRequest.getCategory()); // 分类精确匹配
        queryWrapper.like(StrUtil.isNotBlank(dictQueryRequest.getContent()), "content", dictQueryRequest.getContent()); // 内容模糊查询
        queryWrapper.like(StrUtil.isNotBlank(dictQueryRequest.getTags()), "tags", dictQueryRequest.getTags());
        queryWrapper.like(StrUtil.isNotBlank(dictQueryRequest.getTemplateKeys()), "templateKeys", dictQueryRequest.getTemplateKeys());

        // 时间范围查询（示例：创建时间大于等于指定时间）
        if (ObjUtil.isNotNull(dictQueryRequest.getCreateTime())) {
            queryWrapper.ge("createTime", dictQueryRequest.getCreateTime());
        }

        // 排序处理
        String sortField = dictQueryRequest.getSortField();
        String sortOrder = dictQueryRequest.getSortOrder();
        if (StrUtil.isNotBlank(sortField) && StrUtil.isNotBlank(sortOrder)) {
            // 建议添加排序字段白名单校验
            String safeSortField = sortField.replaceAll("[^a-zA-Z0-9_]", "");
            queryWrapper.orderBy(true,
                    sortOrder.equalsIgnoreCase("asc"),
                    StrUtil.toUnderlineCase(safeSortField));
        }

        return queryWrapper;
    }
}




